package login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csc.usermanagement.dao.UserManagementDbConnector;

/**
 * Servlet implementation class LogInServlet
 */
@WebServlet("/LogIn")
public class LogInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogInServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		// Prepare SQL statements.
		String querySQL = "select * from user where UserName = ? and Password = ?";

		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet resultSet = null;

		try {
			conn = UserManagementDbConnector.getConnection();
			stmt = conn.prepareStatement(querySQL);
			stmt.setString(1, username);
			stmt.setString(2, password);
			resultSet = stmt.executeQuery();
			// Account existed.
			if (resultSet.next()) {
				String type = resultSet.getString("Type");
				request.getSession().setAttribute("username", username);
				request.getSession().setAttribute("password", password);
				request.getSession().setAttribute("type", type);
				request.getRequestDispatcher("LogInSuccess.jsp").forward(request, response);
			} else {
				request.setAttribute("message", "Invalid Username or Password! Please try again!");
				request.getRequestDispatcher("LogIn.jsp").forward(request, response);
			}

			resultSet.close();
			stmt.close();
			conn.close();
		} catch (SQLException se) {
			se.printStackTrace();
		}
	}

}
